//vue
const app = new BaseValidateVue({
    el: '#app',
    data() {
        return {
            operList: [],
            houseOfficerList: [],
            isUpdate:false,
            formData: {
                id: '',
                idcId: '',
                houseId: '',
                houseName: '',
                houseType: '1',
                houseProvince: '',
                houseCity: '',
                houseCounty: '',
                houseAddress: '',
                zipCode: '',
                houseOfficer: '',
                reportStatus: '2',
                defaultHouse: '0',
                houseAreas: [
                    {
                        id: '',
                        houseId: '',
                        areaNumber: '',
                        areaName: '',
                        rackNumber: '',
                    },
                ],
                houseLinkInfos: [
                    {
                        id: '',
                        houseId: '',
                        bandWidth: 0,
                        gatewayIp: '',
                        linkType: 1,
                        accessUnit: '',
                    },
                ],
                deHouseAreasIds: [],
                deHouseLinkInfos: [],
            },
            cities: [],
            counties: [],
            provinces: [],
            provinceCityArea: {
                provinceMap: new Map(),
                cityMap: new Map(),
                areaMap: new Map(),
            },
            validateList: [
                new ValidateObject({
                    ruleName: 'house_number_validate',
                    validate: this.houseNumberValidate,
                }),
                new ValidateObject({
                    ruleName: 'area_number_validate',
                    validate: this.areaNumberValidate,
                }),
                new ValidateObject({
                    ruleName: 'house_name_validate',
                    validate: this.houseNameValidate,
                }),
            ],
            originalHouseNumber: forward.getData().houseNumber,
            originalHouseName: forward.getData().houseName,
        }
    },
    methods: {
        createValidateList() {
            return this.validateList;
        },
        addHouseArea() {
            const houseId = this.formData.id
            this.formData.houseAreas.push({
                id: null,
                houseId: houseId,
                areaNumber: '',
                areaName: '',
                rackNumber: '',
            })
        },
        addHouseLinkInfo() {
            const houseId = this.formData.id
            this.formData.houseLinkInfos.push({
                id: null,
                houseId: houseId,
                bandWidth: '',
                gatewayIp: '',
                linkType: '1',
                accessUnit: '',
            })
        },
        async deleteHouseArea(index) {
            const res = await rxPrompt.confirm('你确定要删除吗？删除后就不能恢复了', ['确认', '取消'])
            if (!res) {
                return;
            }
            const {id = ''} = this.formData.houseAreas[index];
            //新增数据直接删除
            if (id != null && id !== '') {
                const res = await baseIdcHouseAreaApi.delete(id);
                if (res.code !== 200) {
                    await rxPrompt.msg(`删除失败,${res.msg}`);
                    return;
                }
            }
            this.formData.houseAreas.splice(index, 1);
        },
        async deleteHouseLinkInfo(index) {
            if (this.formData.houseLinkInfos.length === 1) {
                rxPrompt.msg(`必须保留一个`)
            } else {
                const res = await rxPrompt.confirm('你确定要删除吗？删除后就不能恢复了', ['确认', '取消'])
                if (!res) {
                    return;
                }
                const {id = ''} = this.formData.houseLinkInfos[index];
                //新增数据直接删除
                if (id != null && id !== '') {
                    const res = await baseHouseLinkInfoApi.delete(id);
                    if (res.code !== 200) {
                        await rxPrompt.msg(`删除失败,${res.msg}`);
                        return;
                    }
                }
                this.formData.houseLinkInfos.splice(index, 1);
            }
        },
        async submitForm() {
            if (!await this.$validator.validateAll()) {
                rxPrompt.dangerMsg("输入存在错误！");
                return
            }
            if (await this.ajaxOption({
                res: baseHouseInfoApi.update(this.formData),
                danger: '修改失败',
                success: '修改成功，即将跳转到列表页面',
                callback:()=> {
                   this.isUpdate = true
                }
            })) {
                forward('/basic-data/admin_house_info')
            }
        },
        async ajaxOption({res, danger, success, callback}) {
            const result = await res
            if (!result || result.code !== 200 || result.data !== true) {
                await rxPrompt.dangerMsg(`${danger}: ${result.msg}`)
                return false
            }

            callback instanceof Function && callback()

            // noinspection JSIgnoredPromiseFromCall
            await rxPrompt.successMsg(success)
            return true;
        },
        async houseNumberValidate(val, args) {
            const {idcId = ''} = this.formData;
            if (idcId === '' || val === '' || this.originalHouseNumber == val) {
                return true;
            }
            return await baseHouseInfoApi.selectHouseNumByIdcId(idcId, val);
        },
        async houseNameValidate(val, args) {
            const {idcId = ''} = this.formData;
            if (idcId === '' || val === '' || this.originalHouseName == val) {
                return true;
            }

            if(this.isUpdate) return true;
            return await baseHouseInfoApi.selectHouseNameByIdcId(idcId, val);
        },
        async areaNumberValidate(val, args) {
            const areaNums = this.formData.houseAreas.map(obj => obj.areaNumber);
            let flagArray = [];
            for (var i = 0; i < areaNums.length; i++) {
                if (flagArray[areaNums[i]]) {
                    return false;
                }
                flagArray[areaNums[i]] = true;
            }
            return true;
        },
        checkId({id = null}) {
            return id !== null;
        }
    },
    computed: {
        provinceMapComputed() {
            return this.provinceCityArea.provinceMap
        },
        cityMapComputed() {
            return this.provinceCityArea.cityMap.get(this.formData.houseProvince) || new Map()
        },
        areaMapComputed() {
            return this.provinceCityArea.areaMap.get(this.formData.houseCity) || new Map()
        },
    },
    async mounted() {
        this.provinceCityArea = await provinceCityAreaApi.selectMap()
        this.operList = await baseOperCompanyApi.selectList()
        this.houseOfficerList = await baseHouseOfficerApi.selectList()
        this.formData = _.cloneDeep(forward.getData());
        if (this.formData.houseLinkInfos.length === 0) {
            this.addHouseLinkInfo()
        }
    },

})
